const app = getApp()
const { get, post } = require('../../utils/request')
const { formatTime } = require('../../utils/util')

Page({
  data: {
    post: null,
    isLiked: false
  },

  onLoad(options) {
    if (options.id) {
      this.getPostDetail(options.id)
    }
  },

  // 获取帖子详情
  async getPostDetail(postId) {
    try {
      wx.showLoading({
        title: '加载中...'
      })

      const post = await get(`/community/posts/${postId}`)
      
      // 格式化时间
      post.createdAt = formatTime(new Date(post.createdAt))
      
      this.setData({
        post,
        isLiked: post.isLiked
      })

    } catch (error) {
      console.error('获取帖子详情失败:', error)
      wx.showToast({
        title: '获取帖子详情失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 点赞/取消点赞
  async toggleLike() {
    if (!app.globalData.hasLogin) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    try {
      const { post } = this.data
      await post(`/community/posts/${post.id}/like`)
      
      // 更新本地点赞状态
      this.setData({
        'post.likes': this.data.isLiked ? post.likes - 1 : post.likes + 1,
        isLiked: !this.data.isLiked
      })

    } catch (error) {
      console.error('点赞操作失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 显示评论
  showComments() {
    // TODO: 实现评论功能
    wx.showToast({
      title: '评论功能开发中',
      icon: 'none'
    })
  },

  // 预览图片
  previewImage(e) {
    const { url } = e.currentTarget.dataset
    const { images } = this.data.post
    
    wx.previewImage({
      current: url,
      urls: images
    })
  },

  onShareAppMessage() {
    const { post } = this.data
    return {
      title: post.title,
      path: `/pages/community/detail?id=${post.id}`,
      imageUrl: post.images && post.images.length > 0 ? post.images[0] : ''
    }
  }
}) 